package com.xiaolin.admin.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaolin
 * @description 描述
 * @since 2024/6/6
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)  // 指定要处理的异常
    public List<ValidErrorInfo> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 打印异常信息
        log.error("参数校验异常", e);
        // 封装异常结果
        List<ValidErrorInfo> errs = new ArrayList<>();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach(err -> {
            ValidErrorInfo validErrorInfo = new ValidErrorInfo();
            validErrorInfo.setField(err.getField());
            validErrorInfo.setErrMsg(err.getDefaultMessage());
            errs.add(validErrorInfo);
        });
        return errs;
    }

}
